package com.future.mashibing.class02;

public class code02_Binary {

    /**
     * 注意位运算优先顺序
     * 顺序：<< <<< >> >>> =>& =>|
     *
     * @param args
     */
    public static void main(String[] args) {
        int a = 10;
        int b = 30;
        System.out.println("===");
        printBinary(a);
        System.out.println();
        printBinary(b);
        System.out.println();
        System.out.println(a ^ b);
        System.out.println(~a);
        System.out.println(add(~a, 1));
        System.out.println(minus(a, b));
    }

    /**
     * 打印32位二进制
     *
     * @param num
     */
    private static void printBinary(int num) {
        for (int i = 31; i >= 0; i--) {
            System.out.print((num & (1 << i)) == 0 ? 0 : 1);
        }
    }

    private static int negate(int a) {
        return add(~a, 1);
    }

    private static int add(int a, int b) {
        int sum = a;
        while (b != 0) {
            sum = a ^ b;
            // 括号不能去掉，<<优先于&
            b = (a & b) << 1;
            a = sum;
        }
        return sum;
    }

    /**
     *
     * @param a
     * @param b
     * @return
     */
    private static int minus(int a, int b) {
        return add(a, negate(b));
    }

}
